/**
 * 
 */
package sort.ui.components;

import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import javax.swing.JFrame;
import javax.swing.JPanel;

import sort.record.RandomRecordsFactory;
import sort.record.Record;
import sort.record.Records;

/**
 * @author masaru-gotou
 *
 */
@SuppressWarnings("serial")
public class SortAnimationPanel extends JPanel {
	public static final int LINE_WIDTH=2;
//	private Records records = null;
	
	private Image d_buffer = null;

	public SortAnimationPanel() {
		super(false);	// ダブルバッファリングは自前で実装（早すぎてアニメーションしないため）
		Dimension size = new Dimension(100,100); 
		setMinimumSize(size);
//		setMaximumSize(size);
		setPreferredSize(size);
	}

	public void drawRecords(Records records) {
		if ( d_buffer == null ) {
			d_buffer = createImage(getWidth(),getHeight());
		}
		int lin_w = LINE_WIDTH;
		Graphics g = d_buffer.getGraphics();
		// 画面クリア
		g.clearRect(0, 0, getWidth(), getHeight());
		// 描画
		for (int x=0;x<records.size();x++) {
			Record r = records.get(x);
			g.setColor(Color.CYAN);
			g.fillRect(x*lin_w, 0, lin_w, r.getKey());
			g.setColor(Color.BLUE);
			g.fillRect(x*lin_w,r.getKey(),lin_w,1);
		}
		// ウィンドウを更新する
		getGraphics().drawImage(d_buffer,0,0,this);
	}
	
    private static void createAndShowGUI() {
        //Create and set up the window.
        JFrame frame = new JFrame("SortAnimationPanel Test");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //Create and set up the content pane.
		Container container = frame.getContentPane();
		final SortAnimationPanel panel = new SortAnimationPanel();
        container.add(panel);
        
        panel.addMouseListener(new MouseListener() {

			@Override
			public void mouseClicked(MouseEvent e) {
				Records recs = RandomRecordsFactory.getInstance().create(100);
				panel.drawRecords(recs);
			}

			@Override
			public void mouseEntered(MouseEvent e) {
			}

			@Override
			public void mouseExited(MouseEvent e) {
			}

			@Override
			public void mousePressed(MouseEvent e) {
			}

			@Override
			public void mouseReleased(MouseEvent e) {
			}
        	
        });
        
        //Display the window.
//        frame.pack();
        frame.setSize(100,100);
        frame.setVisible(true);
    }
	/**
	 * @param args
	 */
	public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
	}
}
